// 千万条数据，亿条数据就会崩溃
let arr = []
let len = 10000000
let i = 0 

while (i < len){
    const num = Math.random() * 1000
    arr.push(num)
    i++
}

time(()=>{
    console.log(findMax2(arr))
})



function time(fn) {
    let time1 = new Date().getTime()
    fn()
    let time2 = new Date().getTime()

    console.log("use time:", time2-time1)
}


// 二分查找，无需数据没有提升效率
function findMax (arr) {
    // 1亿条数据中找到最大的数
    const len = arr.length;//00000
    const half = len/2
    let i = 0

    if(arr.length < 2){
        return arr[0]
    }

    if(arr.length === 2) {
        if(arr[0] > arr[1]){
            return arr[0]
        } else {
            return arr[1]
        }
    }

    const left = findMax(arr.slice(0, half))
    const right = findMax(arr.slice(half, len))
    
    if(left > right) 
        return left
    else 
        return right 
}

// 直接循环更快
function findMax2 (arr) {
    let max = 0

    arr.forEach(element => {
        max = element > max?element:max
    });
    
    return max
}